package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.Answer;
import cn.wolfcode.trip.base.domain.AskQuestions;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IAskQuestionsService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/askQuestions")
public class AskQuestionsController {

    @Autowired
    private IAskQuestionsService askQuestionsService;

    //所有的问答
    @GetMapping
    @ResponseBody
    public Object list(QueryObject qo) {
        PageInfo<AskQuestions> pageInfo = askQuestionsService.query(qo);
        return pageInfo;
    }

    //保存提问
    @PostMapping
    @ResponseBody
    public Object save(AskQuestions askQuestions) {
        JSONResult result = new JSONResult();
        //内容不能不写
        if(askQuestions.getContent()==null){
            result.mark("不能为空");
            return result;
        }
        try {
            askQuestions.setUser(UserContext.getCurrentUser());
            askQuestionsService.save(askQuestions);

        } catch (Exception e) {
            e.printStackTrace();
            result.mark("失败");
        }
        return result;
    }

    //保存回复
    @PostMapping("/answer")
    @ResponseBody
    public Object saveAnswer(Answer answer) {
        JSONResult result = new JSONResult();
        //内容不能不写
        if(answer.getContent()==null){
            result.mark("不能为空");
            return result;
        }
        try {
            answer.setUser(UserContext.getCurrentUser());
            askQuestionsService.saveAnswer(answer);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("失败");
        }
        return result;
    }

    //某个提问的所有的回复
    @GetMapping("/answer")
    @ResponseBody
    public Object listAnswer(Long quesId) {
        AskQuestions question = askQuestionsService.get(quesId);
        List<Answer> answers = askQuestionsService.listAnswer(quesId);
        Map<String, Object> map = new HashMap<>();
        map.put("question",question);
        map.put("answers",answers);
        return map;
    }
}
